package cn.sskxyz.security.authorization.config;

import cn.sskxyz.security.core.property.SecurityProperties;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.RSAKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

@Configuration
public class JwkSetConfigure {

    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 转换公钥为jwkset对象
     * @return
     * @throws Exception
     */
    @Bean
    public JWKSet jwkSet() throws Exception {
        byte[] bytesPub = Base64.getDecoder().decode(securityProperties.getJwtKeyPair().getPublicKey());
        X509EncodedKeySpec publicKey = new X509EncodedKeySpec(bytesPub);
        KeyFactory factory = KeyFactory.getInstance("RSA");

        RSAPublicKey rsaPublicKey = (RSAPublicKey) factory.generatePublic(publicKey);
        RSAKey key = new RSAKey.Builder(rsaPublicKey)
                .keyUse(KeyUse.SIGNATURE)
                .algorithm(JWSAlgorithm.RS256)
                .keyID(securityProperties.getJwtKeyPair().getKeyId())
                .build();
        return new JWKSet(key);
    }
}
